package com.shuqi.model;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.content.Context;

import com.shuqi.common.MyTask;
import com.shuqi.common.Urls;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.net.HttpRequest;
import com.shuqi.model.net.UrlManager;
import com.shuqi.model.net.listener.HttpRequestListener;
import com.shuqi.model.parse.parser.FeedBackParser;

/**
 * 意见反馈model
 * 
 * @author zhuchen
 * 
 */
public class FeedBackModel extends ModelBase implements HttpRequestListener {

    private HttpRequest httpRequest;
    private Context context;
    private String content;
    private String contact;
    private String action;
    private int pageIndex = 1;

    public FeedBackModel(Context context) {
        this.context = context;
    }

    @Override
    public void action(int actionCode, Object object) {
        fireEvent(actionCode, object);
    }

    @Override
    public List<BasicNameValuePair> setParams() {
        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        try {
            params.add(new BasicNameValuePair("content", URLEncoder.encode(content, "utf-8")));
            params.add(new BasicNameValuePair("contact", URLEncoder.encode(contact, "utf-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return params;
    }

    @Override
    public String getRequestUrl() {
        return Urls.getFeedBackInsertURL(action, MyAccountManager.getInstance(context).getUserId(),
                pageIndex);
    }

    @Override
    public void loadData(Object... objs) {
        this.action = (String) objs[0];
        if (action.equals("submit") && objs.length > 2) {
            this.action = (String) objs[0];
            this.content = (String) objs[1];
            this.contact = (String) objs[2];
            httpRequest =
                    new com.shuqi.model.net.HttpRequest(context, UrlManager.COLUMN_DOMAIN_WRITE,
                            getRequestUrl(), setParams(), this);
            httpRequest.setDataParseAdapter(new FeedBackParser());
            MyTask.runInBackground(httpRequest, true);
        } else if (action.equals("request")) {
            if (objs.length > 1) {
                this.action = (String) objs[0];
                this.pageIndex = (Integer) objs[1];
                httpRequest =
                        new com.shuqi.model.net.HttpRequest(context, UrlManager.COLUMN_DOMAIN_WRITE,
                                getRequestUrl(), null, this);
                httpRequest.setDataParseAdapter(new FeedBackParser());
                MyTask.runInBackground(httpRequest, true);
            }
        }

    }

    @Override
    public void onDestroy() {
        if (httpRequest != null) {
            httpRequest.abort();
        }
    }

}
